import React, { useState } from "react";
import { Button, Input, Form } from "react-vant";
import { useNavigate } from "react-router-dom";
import { Checkbox } from "react-vant";
import { CenterPopup } from "antd-mobile";
import axios from "axios";
import { PhoneO } from "@react-vant/icons";
export default () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  //复选框状态
  const [checked, setChecked] = React.useState(false);
  //弹出框显示
  const [visible, setVisible] = useState(false);
  //获取验证码
  const hqyzm = async () => {
    const res = await axios.get("/api/login/code");
    const { data } = res;
    console.log(data);
    //赋值到input框中
    form.setFieldsValue({ code: data });
  };
  const onFinish = async (values: any) => {
    const { phone, code } = values;
    console.log(values);
    //判断是否同意协议
    if (!checked) {
      setVisible(true);
      return;
    }
    const res = await axios.post("/api/login/phone", {
      phone,
      code,
    });
    console.log(res.data);
    const { code1, data, token } = res.data;
    if (code1 == 200) {
      navigate("/my");
      localStorage.setItem("token", token);
      localStorage.setItem("phone", data);
    } else {
      alert("验证码错误或手机号错误");
    }
  };
  return (
    <div className="box">
      <CenterPopup
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
        }}
      >
        <div>请先阅读并同意《用户协议》 《隐私政策》</div>
      </CenterPopup>
      <Form
        form={form}
        onFinish={onFinish}
        footer={
          <div style={{ margin: "16px 16px 0" }}>
            <Button round nativeType="submit" type="primary" block>
              登录
            </Button>
          </div>
        }
      >
        <Form.Item
          tooltip={{
            message:
              "A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.",
          }}
          rules={[{ required: false, message: "请填写用户名" }]}
          name="phone"
        >
          <Input placeholder="请输入中国大陆手机号" className="inp" />
        </Form.Item>
        <Form.Item
          rules={[{ required: false, message: "请填写验证码" }]}
          name="code"
        >
          <Input placeholder="填写短信验证码" className="inp" />
          <Button className="btn" onClick={() => hqyzm()}>
            获取验证码
          </Button>
        </Form.Item>
        <Form.Item>
          <Checkbox checked={checked} onChange={setChecked}>
            我已阅读并同意 《用户协议》 《隐私政策》
          </Checkbox>
        </Form.Item>
      </Form>
    </div>
  );
};
